<template>
  <div class="category-selector">
    <!-- 简单模式：单个下拉选择器，显示层级 -->
    <el-select
        v-if="mode === 'simple'"
        :model-value="modelValue"
        :placeholder="placeholder"
        :style="{ width: width }"
        clearable
        filterable
        @clear="handleClear"
        @update:model-value="handleChange"
    >
      <el-option
          v-for="category in flatCategories"
          :key="category.id"
          :label="getCategoryDisplayName(category)"
          :value="category.id"
      >
        <span :style="{ paddingLeft: (category.level - 1) * 16 + 'px' }">
          {{ category.name }}
        </span>
      </el-option>
    </el-select>

    <!-- 级联模式：级联选择器 -->
    <el-cascader
        v-else-if="mode === 'cascader'"
        :model-value="cascaderValue"
        :options="treeCategories"
        :placeholder="placeholder"
        :props="cascaderProps"
        :style="{ width: width }"
        clearable
        filterable
        @update:model-value="handleCascaderChange"
    />

    <!-- 分组模式：按一级分类分组 -->
    <el-select
        v-else-if="mode === 'group'"
        :model-value="modelValue"
        :placeholder="placeholder"
        :style="{ width: width }"
        clearable
        filterable
        @clear="handleClear"
        @update:model-value="handleChange"
    >
      <el-option-group
          v-for="firstCategory in firstLevelCategories"
          :key="firstCategory.id"
          :label="firstCategory.name"
      >
        <el-option
            :label="firstCategory.name"
            :value="firstCategory.id"
        />
        <el-option
            v-for="subCategory in getSubCategories(firstCategory.id)"
            :key="subCategory.id"
            :label="`　　${subCategory.name}`"
            :value="subCategory.id"
        />
      </el-option-group>
    </el-select>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue'
import {useCategoryStore} from '@/store/category'

// Props
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: null
  },
  mode: {
    type: String,
    default: 'simple', // simple | cascader | group
    validator: (value) => ['simple', 'cascader', 'group'].includes(value)
  },
  placeholder: {
    type: String,
    default: '请选择分类'
  },
  width: {
    type: String,
    default: '200px'
  },
  includeAll: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// Store
const categoryStore = useCategoryStore()

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: false,
  checkStrictly: true
}

// 级联选择器的值（需要转换为数组格式）
const cascaderValue = ref([])

// 计算属性
const flatCategories = computed(() => {
  let categories = categoryStore.categories.filter(cat => cat.status === 1)

  if (props.includeAll) {
    categories = [
      {id: null, name: '全部分类', level: 0},
      ...categories
    ]
  }

  return categories.sort((a, b) => {
    if (a.level !== b.level) return a.level - b.level
    return a.sortOrder - b.sortOrder
  })
})

const firstLevelCategories = computed(() => {
  return categoryStore.categories.filter(cat => cat.level === 1 && cat.status === 1)
})

const treeCategories = computed(() => {
  const buildTree = (categories, parentId = 0) => {
    return categories
        .filter(cat => cat.parentId === parentId && cat.status === 1)
        .sort((a, b) => a.sortOrder - b.sortOrder)
        .map(cat => ({
          id: cat.id,
          name: cat.name,
          children: buildTree(categories, cat.id)
        }))
  }
  return buildTree(categoryStore.categories)
})

// 方法
const getCategoryDisplayName = (category) => {
  if (category.level === 0) return category.name
  const prefix = '　'.repeat((category.level - 1) * 2)
  return `${prefix}${category.name}`
}

const getSubCategories = (parentId) => {
  return categoryStore.categories.filter(cat =>
      cat.parentId === parentId && cat.status === 1
  ).sort((a, b) => a.sortOrder - b.sortOrder)
}

const handleChange = (value) => {
  emit('update:modelValue', value)
  emit('change', value)
}

const handleClear = () => {
  emit('update:modelValue', null)
  emit('change', null)
}

const handleCascaderChange = (value) => {
  const categoryId = Array.isArray(value) ? value[value.length - 1] : value
  emit('update:modelValue', categoryId)
  emit('change', categoryId)
}

// 初始化分类数据
const initCategories = async () => {
  if (categoryStore.categories.length === 0) {
    try {
      await categoryStore.getCategoryList({
        current: 1,
        size: 1000,
        status: 1
      })
    } catch (error) {
      console.error('加载分类数据失败:', error)
    }
  }
}

// 监听 modelValue 变化，更新级联选择器的值
watch(() => props.modelValue, (newValue) => {
  if (props.mode === 'cascader' && newValue) {
    // 构建级联路径
    const category = categoryStore.categories.find(cat => cat.id === newValue)
    if (category) {
      const path = []
      if (category.level === 2) {
        path.push(category.parentId)
      }
      path.push(category.id)
      cascaderValue.value = path
    }
  } else {
    cascaderValue.value = []
  }
}, {immediate: true})

// 组件挂载时初始化数据
onMounted(() => {
  initCategories()
})
</script>

<style scoped>
.category-selector {
  display: inline-block;
}

:deep(.el-select-dropdown__item) {
  padding-left: 0;
}

:deep(.el-option-group__title) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
</style>
